package com.xzp.blog.interceptor;

import com.xzp.blog.entity.Admin;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.xzp.blog.consts.SessionConstants.SESSION_ADMIN_CURRENT_USER;

/**
 * 用户权限验证拦截器
 */
@Component
public class UserAuthenticationInterceptor implements HandlerInterceptor {
    /**
     *如果是管理员则返回true
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object obj = request.getSession().getAttribute(SESSION_ADMIN_CURRENT_USER);
        if (obj == null || ! (obj instanceof Admin)){
            //如果没有以管理员身份登录
            response.sendRedirect(request.getContextPath() + "/adminlogin");  //重定向到管理员登陆界面
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
